package com.studentManagement.servlet;

import com.aliyuncs.exceptions.ClientException;
import com.studentManagement.dao.TeacherDao;
import com.studentManagement.daoImpl.TeacherDaoImpl;
import com.studentManagement.po.Teacher;
import com.studentManagement.utils.SMSCodeUtil;
import com.studentManagement.utils.SendSMSUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.mail.Session;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@WebServlet(name = "TeacherServlet")
public class TeacherServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");
        if (action.equals("updateTeacherInfo")) {
            updateTeacherInfo(request, response);//更新teacher基本信息
        }else if(action.equals("modifyPhoneSendSMS")){
            modifyPhoneSendSMS(request, response);//发送验证码到手机
        }else if(action.equals("veritySMSCode")){
            veritySMSCode(request, response);//比较验证码是否相同
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    /**
     * 方法的功能描述：更新teacher基本信息
     * @params：[request,response]
     * @return:void
     */
    private void updateTeacherInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Teacher teacher = (Teacher) request.getSession().getAttribute("teacher");
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {
            try {
                DiskFileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                upload.setHeaderEncoding("utf-8");
                upload.setSizeMax(10 * 1024 * 1024);

                List<FileItem> formItems = upload.parseRequest(request);
                Iterator<FileItem> iter = formItems.iterator();
                //依次处理每个表单域
                while (iter.hasNext()) {
                    FileItem item = iter.next();
                    //处理普通表单
                    if (item.isFormField()) {
                        if ("teacher_name".equals(item.getFieldName()))
                            teacher.setTeacher_name(item.getString("utf-8"));
                        if ("teacher_sex".equals(item.getFieldName()))
                            teacher.setTeacher_sex(Integer.parseInt(item.getString("utf-8")));
                        if ("teacher_age".equals(item.getFieldName()))
                            teacher.setTeacher_age(Integer.parseInt(item.getString("utf-8")));
                    }
                    //处理文件表单
                    else {
                        //获得文件名及路径
                        String fileName = item.getName();
                        String suffix = fileName.substring(fileName.indexOf(".") + 1).toLowerCase();
                        //图片格式判断
                        if (fileName != null && fileName.indexOf(".") != -1) {
                            if (suffix.equals("jpeg") || suffix.equals("jpg") || suffix.equals("gif") || suffix.equals("png") || suffix.equals("bmp") || suffix.equals("tiff")) {
                                String name = new Date().getTime() + "." + fileName.substring(fileName.indexOf(".") + 1);
                                //如果目录不存在，则创建
                                File catalog = new File(getServletContext().getRealPath("/resources/images/upload"));
                                if (!catalog.exists()) catalog.mkdirs();

                                File fullFile = new File(catalog, name);
                                teacher.setTeacher_image_Path(name);
                                item.write(fullFile);
                                new TeacherDaoImpl().updateTeacher(teacher, teacher.getTeacher_id());
                                request.setAttribute("message", "提交成功");
                            } else {
                                request.setAttribute("message", "请上传 jpeg/jpg/gif/png/bmp/tiff 格式的图片");
                                request.getServletContext().getRequestDispatcher(request.getContextPath() + "/jsp/teacher/myInfo/myInfo.jsp").forward(request, response);
                            }

                        } else {
                            teacher.setTeacher_image_Path(teacher.getTeacher_image_Path());
                            new TeacherDaoImpl().updateTeacher(teacher, teacher.getTeacher_id());
                            request.setAttribute("message", "提交成功");
                        }
                        item.delete();
                    }
                }
            } catch (Exception e) {
                e.getStackTrace();
                request.setAttribute("message", "错误信息: " + e.getMessage());
            }

            // 跳转到 myInfo.jsp
            request.setAttribute("teacher", teacher);
            request.getServletContext().getRequestDispatcher(request.getContextPath() + "/jsp/teacher/myInfo/myInfo.jsp").forward(request, response);
        }

    }




    private void modifyPhoneSendSMS(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        //获取手机号
        String tel=request.getParameter("tel");
        String SMSCode="";
        try {
            //发送验证码
            SMSCode=sendSMS(tel);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        request.getSession().setAttribute(tel,SMSCode);
        request.getSession().setMaxInactiveInterval(60*5);
    }
    /**
    * 方法的功能描述：向手机号发送验证码
    * @params：tel：手机号
    * @return:String：验证码 */
    private String sendSMS(String tel) throws ClientException {
        SendSMSUtil sendSMSUtil=new SendSMSUtil();
        String SMSCode=new SMSCodeUtil().getSMSCode(6);
        sendSMSUtil.send(tel,SMSCode);
        return SMSCode;
    }
    /**
    * 方法的功能描述：验证短信代码是否相同，相同则更新手机号，不同返回验证码错误
    * @params：
    * @return:  */
    private void veritySMSCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out=response.getWriter();
        String tel =request.getParameter("tel");
        String inCode=request.getParameter("code");
        String outCode= (String) request.getSession().getAttribute(tel);
        if(inCode.equals(outCode)){
            Teacher teacher= (Teacher) request.getSession().getAttribute("teacher");
            teacher.setTeacher_phone(tel);
            try {
                new TeacherDaoImpl().updateTeacher(teacher,teacher.getTeacher_id());
                out.print("true");
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }else if(outCode==null||outCode.length()==0){
            out.print("overtime");
        }
        else{
            out.print("false");
        }
    }
}